import React, { Component } from 'react';
import { observer,inject } from 'mobx-react';
import { Route, withRouter, Switch } from 'react-router-dom';
import moment from 'moment';
import { TabPage, Browser, RouteLayout } from 'weaver-mobile-page';
import { Icon, Tools, DateSwitch, Bubble } from 'weaver-mobile';
import * as Api from '../../api/roomPlan';
import MeetingUtil from '../../util/meetingUtil';
import RoomUsedDetail from '../../components/roomPlan/roomUsedDetail';
const getLabel = Tools.getLabel;

@inject('roomPlanStore')
@inject('viewMeetingStore')
@withRouter
@observer
export default class Demo extends Component {
  constructor(props) {
    super(props);
    this.state = {
      currentdate: '', // 当前时间
      rooms: [],
      roomName: '',
      roomId: '',
      pageTabKey: '',
      roomMeetAllTabs: [],  // tab中所有tab,方便根据查询会议室进行过滤
      roomMeetAllID: [],  // tab中所有对应tab的ID,方便根据查询会议室进行过滤
      roomMeetTabs: [],  // roomTabs中的会议和roomid中会议id一一对应
      roomMeetID: [],
      useMap: {}, // key为roomid,value为使用信息
      duration: 0, // 最小间隔时间
      dspUnit: 0, // 一个小时分成dspUnit个单元
      visible: 'none', // loading图标
      scrollTop: 0,
      nowTabIndex:0,
      nowTab:[],
    };
  }
  //会议室使用情况逻辑
  //1:初始化时首先根据query的值来确认selectDate,再根据sessionStorage去判断,最后采用当前时间
  //2:查询出来筛选的时候根据筛选出来的roomid来进行后台取值
  //3:切换tab的时候就是根据useMap,从这里面将选中的key筛选出来
  //4:支持刷新,但是只支持选中日期刷新,筛选出来的数据在刷新的时候还是会还原成默认所有数据
  componentDidMount() {
    const {roomPlanStore } = this.props;
    const selectDate = this.props.location&&this.props.location.query&&this.props.location.query.selectDate
    let params = {}
    if(selectDate && selectDate.length > 0){
      this.setState({currentdate:selectDate}) 
      sessionStorage.setItem('meetingRoomPlanDate',selectDate)
      params = {currentdate:selectDate}
    }else{
      if(sessionStorage&&sessionStorage.meetingRoomPlanDate){
        this.setState({currentdate:sessionStorage.meetingRoomPlanDate})
        params = {currentdate:sessionStorage.meetingRoomPlanDate}
      }else{
        this.setState({currentdate:moment(new Date()).format("YYYY-MM-DD")})
        sessionStorage.setItem('meetingRoomPlanDate',moment(new Date()).format("YYYY-MM-DD"))
        params = {currentdate:moment(new Date()).format("YYYY-MM-DD")}
      }
    }
    roomPlanStore.initData();
    roomPlanStore.initRoomBrowser(this.props.location.pathname);
    this.getRoomUsedInfo(params,true);
  }
  //
  componentWillUnmount() {
    sessionStorage.removeItem('meetingRoomPlanDate')
  }

  // 获得会议室使用时间段
  getTableHourInfo = (startHour, endHour) => {
    let tableHours = [];
    if(endHour-startHour > 0){
      for(startHour; startHour <= endHour; startHour++){
        tableHours.push(startHour.toString() + ':00 - '+(startHour+1).toString() + ':00');
      }
    }
    return {tableHours: tableHours};
  }

  // 创建会议室使用情况的每一列tr
  createTrList = (time,key) => {
    let trContent = [];
    let roomid = this.state.roomId;
    let t = parseInt(time.replace(':',''),10);
    let { useMap, dspUnit, duration,  } = this.state;
    let counting = dspUnit;
    let startTime = 0, endTime = 0;
    let T = t;
    if(useMap && useMap[roomid]){
      startTime = parseInt(useMap[roomid][0].time.replace(':',''),10);
      let len = useMap[roomid].length;
      endTime = parseInt(useMap[roomid][len-1].time.replace(':',''),10);
    }
    // 渲染前面空白单元格
    while(T < startTime && --counting >= 0) {
      let tt = T;
      let hour = Math.floor(tt/100) + ":";
      let minute = tt%100;
      let minuteSta = hour + (minute>9 ? ''+minute : "0"+minute); 
      let minuteEnd = hour + ((minute+duration-1)>9 ? ''+(minute+duration-1) : "0"+(minute+duration-1)); 
      trContent.push(<div starttime={minuteSta} endtime={minuteEnd} key={T}></div>);
      T = T + duration;
    }
    // 渲染有会议单元格
    T = t;
    useMap && useMap[roomid] && useMap[roomid].forEach((res, index) => {
      let meetingInfo = [];
      let tt = parseInt(res.time.replace(':',''),10)
      res && res.meetings && res.meetings.map((res) => {
        meetingInfo.push(res.id);
        return meetingInfo;
      });
      if(T <= tt && tt < T+100){
        let hour = Math.floor(tt/100) + ":";
        let minute = tt%100;
        let minuteSta = hour + (minute>9 ? ''+minute : "0"+minute); 
        let minuteEnd = hour + ((minute+duration-1)>9 ? ''+(minute+duration-1) : "0"+(minute+duration-1)); 
        let content = res.meetings.length > 1 ? (res.meetings.length+getLabel(391342,"个会议")) : '';
        trContent.push(
          <div satrttime={minuteSta} endtime={minuteEnd} key={index} style={{backgroundColor: res.bgcolor, color: res.fontcolor || '#000'}} meetingidarray ={meetingInfo}
          onClick={(e) => {this.previewMeetingInfo(e.target)}}>
            {content}
          </div>);
      }
    });  
    // 渲染后面空白单元格
   
    let count = (T+100 > endTime && endTime > T) ? (endTime - T)/duration +1 : 0;
    counting === 1 && (count = 1) // 当间隔为1时，避免重复渲染空白
    let tt = endTime + duration;
    while(T+100 > endTime && T < 2400 && (--counting)-count >= 0 ) {
      tt = (endTime>T) ? tt : T;  
      let hour = Math.floor(tt/100);
      hour = hour>9 ? ''+hour : "0"+hour
      hour = hour + ":"
      let minute = tt%100;
      let minuteSta = hour + (minute>9 ? ''+minute : "0"+minute); 
      let minuteEnd = hour + ((minute+duration-1)>9 ? ''+(minute+duration-1) : "0"+(minute+duration-1)); 
      trContent.push(<div starttime={minuteSta} endtime={minuteEnd} key={T} onClick={()=>{this.createMeeting(minuteSta,minuteEnd)}}></div>);
      tt = tt+duration;
      T = T + duration;
    }
    return (trContent); 
  }

  createMeeting = (startTime,endTime)=>{
    const{ from } = this.props
    if(from === 'calendar'){
      const { onlyFlowCreate, hideCreateEntry, workflowBaseIds,requestFieldIds,} = this.props.viewMeetingStore;
      sessionStorage.setItem('type','create');
      let workflowBaseIdsArr = workflowBaseIds.split(',')
      if(hideCreateEntry == 1){
        return;
      }else if(onlyFlowCreate == 1 && hideCreateEntry ==0 && workflowBaseIdsArr.length === 0){
        Bubble.error(getLabel(510049, '请通过流程新建会议！'), 1, { top: '50%' });
      }else if(onlyFlowCreate == 1 && hideCreateEntry ==0 && workflowBaseIdsArr.length > 1){
        this.props.history.push({pathname:`/meeting/createRequest`,query:{iscreate:'1',workflowid:workflowBaseIds}});
      }else if(onlyFlowCreate == 1 && hideCreateEntry ==0 && workflowBaseIdsArr.length === 1){
        this.props.history.push({pathname:`/meeting/addRequest`,query:{isNeedTab:0,wfRange:workflowBaseIds}});
      }else{
        this.props.history.push({pathname:`/calendar/detail`,query:{
          meetingid:'',
          type:'create',
          roomPlanSelectDate:this.state.currentdate,
          meetingRoomBeginTime:startTime,
          meetingRoomEndTime:endTime,
        }});
      }
    }
  }

 
  // 查询会议室使用使用情况，显示颜色等
  getRoomUsedInfo = (params,isinit=false) => {
    // params = {...params, currentdate: this.state.currentdate}
    const roomMeetingIDs = this.state.roomMeetID
    let meetingIdsArr = []
    //当参数包含roomid的时候是筛选会议室的时候,如果没有选择任何会议室或者在会议室浏览按钮中是选中的清楚选项,那么就取得所有
    //不包含会议室的时候是改变日期根据会议室tab中显示的会议室ID来决定
    //个人感觉两边参数格式不一致,下次时间充裕的时候优化
    if(!params.roomid){
      roomMeetingIDs && roomMeetingIDs.map((item,index)=>{
        return meetingIdsArr.push(item.id)
      })
      if(meetingIdsArr.length > 0){
        params = {...params,roomid:meetingIdsArr.join(',')}
      }
    }
    
    this.setState({visible: 'block'});
    Api.getRoomReportData(params).then((res) => {
      this.setState({visible: 'none'});
      let dspUnit = res.dspUnit;
      let duration = 60 / res.dspUnit;
      let useMap = {};
      let arrRoom = [];
      let arrID = [];
      // 查询会议室
      res && res.rooms && res.rooms.map(key => {
        let objRoom = {};
        let objID = {};
        objRoom.title = key.name;
        objRoom.key = key.id;
        objID.id = key.id;
        arrRoom.push(objRoom);
        arrID.push(objID);
        return 0;
      });
      // 会议室中会议信息
      res.datas && res.datas.forEach((obj) => {
        if(!obj.roomid) return;
        useMap[obj.roomid] = obj.info;
      });
      this.setState({
        // roomId: arrID[0].id,
        useMap: useMap,
        duration: duration,
        dspUnit: dspUnit,
        roomMeetTabs: arrRoom,  // roomTabs中的会议和roomid中会议id一一对应
        roomMeetID: arrID,
      });
        

      if(isinit){
        this.setState({
          roomMeetAllTabs: arrRoom,  // roomTabs中的会议和roomid中会议id一一对应
          roomMeetAllID: arrID,
        });
        if(this.state.roomId === ''){
          this.setState({
            roomId: arrID[0].id
          });
        }
      }
      
    });
  }

  previewMeetingInfo = (params) => {
    //会议室使用情况使用的场景
    //1:会议信息中
    //2:会议日历右下角
    const nowPathName = this.props.location.pathname
    this.props.history.push(`${nowPathName}/roomUsedDetail`)
    const { getRoomMeetingList} = this.props.roomPlanStore;
    let meetingIDArr = [];
    meetingIDArr = params.getAttribute('meetingidarray')
    // getRoomReportList({roomid:meetingIDArr})
    getRoomMeetingList({meetingIds: meetingIDArr})
  }

  getHeight = () => {
    return document.body.clientHeight - MeetingUtil.getTabHeight() - 44*MeetingUtil.getBaseHeight();
  }

  onChange = (date) => {
    this.setState({
      currentdate: date,
    });
    sessionStorage.setItem('meetingRoomPlanDate',date)
    this.getRoomUsedInfo({currentdate: date},false);
  }

  changeRoomMeetTab = (params) => {
    //如果为空,那么就是选中了清除按钮或者什么都没有选择,那么这时候就要取得allTab中的会议室ID
    if(!params){
      const roomMeetingIDs = this.state.roomMeetAllID
      let meetingIdsArr = []
      roomMeetingIDs && roomMeetingIDs.map((item,index)=>{
        return meetingIdsArr.push(item.id)
      })
      params = meetingIdsArr.join(',')
      
    }
    this.getRoomUsedInfo({currentdate: this.state.currentdate,roomid:params},false);
    let arrTabTemp = [];
    let arrIdTemp = [];
    let arr = [];
    if(params) {
      const { roomMeetAllID,roomMeetAllTabs } = this.state;
      arr = params.split(',');
      roomMeetAllID.map((key,index)=>{
        return arr.map((str) => {
          if(str === key.id){
            arrTabTemp.push(roomMeetAllTabs[index])
            arrIdTemp.push(roomMeetAllID[index])
          }
        });
      })
      this.setState({
        roomMeetTabs : arrTabTemp,
        roomMeetID : arrIdTemp,
      })
    }else{
      this.setState({
        roomMeetTabs : this.state.roomMeetAllTabs,
        roomMeetID : this.state.roomMeetAllID,
      })
    }
    //计算当前选中tab的index,如果存在就显示之前的tab,不存在就默认显示index=0
    let contain = false;
    let tempIndex = {}
    const { nowTab } = this.state
    if(arrTabTemp.length > 0){
      arrTabTemp.map((key,index)=>{
        if(key.key === nowTab.key){
          tempIndex.index = index;
          tempIndex.tab = key;
          contain = true;
        }
      })
    }
    if(!contain){
      //如果不包含的情况下,那么只能取筛选后的第一条数据,以及对应的第一条数据的roomid
      this.setState({
        nowTabIndex : 0,
        nowTab : arrTabTemp[0],
        roomId : arrTabTemp[0].key,
      })
    }else{
      this.setState({
        nowTabIndex : tempIndex.index,
        nowTab : tempIndex.tab,
      })
    }
  }

  render() {
    const { roomPlanStore } = this.props;
    const { color, startHour, endHour, browser1} = roomPlanStore; 
    let { tableHours } = this.getTableHourInfo(startHour,endHour); 
    const { roomMeetTabs, roomMeetID, visible} = this.state;
    const tabProps = {
      onTabClick: (tab,index) => {
        let roomId = roomMeetID[index].id;
        this.setState({
          roomId: roomId,
          nowTabIndex:index,
          nowTab : tab,
        });
      },
      page:this.state.nowTabIndex,
    }
    const defaultTabBarProps = {
      activeTab:this.state.nowTabIndex,
    }
    return (
      <div>
        <Icon type="loading" style={{zIndex:'9999',position: 'absolute', left: '50%', top: '50%',display: visible}}/>
        <div className="roomplan-top-container">
          <TabPage
            tabs={roomMeetTabs}
            btns={[
              <Browser
                label='browser'
                store={browser1}
                hasAdvanceSerach
                isSingle={false}
                type={184}
                onChange={(arg) => {
                  this.changeRoomMeetTab(arg)
                }}
              >
                <Icon type='filter-o'/>
              </Browser>
            ]}
            span={[7,2]}
            tabProps={tabProps}
            defaultTabBarProps={defaultTabBarProps}
            >
          </TabPage>
          <div className="legend">
            <div style={{paddingTop: 5}}>
            {this.state.currentdate !== '' ?<DateSwitch date={new Date(this.state.currentdate)} defaultValue onChange={date => this.onChange(date)} />:''}
            </div>
            <div className="wea-meetingRoom-cirlceSpan" title={getLabel(383468,"占用")}>
              <div className="square" style={{backgroundColor: color.usedColor,height:10,width:10,borderRadius:'50%'}}/>
              <div className='squareName'>{getLabel(383468,"占用")}</div>
            </div>
            <div className="wea-meetingRoom-cirlceSpan" title={getLabel(2242,"待审批")}>
              <div className="square" style={{backgroundColor: color.agreementColor,height:10,width:10,borderRadius:'50%'}}/>
              <div className='squareName'>{getLabel(2242,"待审批")}</div>
            </div>
            <div className="wea-meetingRoom-cirlceSpan" title={getLabel(127867,"冲突")}>
              <div className="square" style={{backgroundColor: color.conflictedColor,height:10,width:10,borderRadius:'50%'}}/>
              <div className='squareName'>{getLabel(127867,"冲突")}</div>
            </div>
          </div>
        </div>
        <div className={'room-use-detail-div'}>
          <div style={{height: this.getHeight(),overflow:'auto'}}>
            {/* 会议室使用情况列表 */}
            <table className='room-plan-tab-header'>
              <tbody>
              {tableHours && (tableHours.map((time,key)=> {
                return (
                  <tr className='roomplan-list-item-display' key={key} >
                  <td key={2*key} className='roomplan-time-label'>{time}</td>
                  <td key={2*key+1}>       
                    {this.createTrList(time,key)}
                  </td>
                  </tr>);
                })) } 
              </tbody>
            </table>
          </div>
        </div>


        <Switch>
          <Route
            key="roomUsedDetail"
            path="/calendar/*/roomPlan/roomUsedDetail"
            render={()=>(
              <RouteLayout>
              <div key="roomUsedDetailDiv" className="wm-route-layout wm-demo-route-layout-page">
                <RoomUsedDetail />
              </div>
              </RouteLayout>
            )}
          />
          
        </Switch>

      </div>
    );
  }
}